/*
 * @Description: 权限管理相关文件
 * @Version: 1.0
 * @Author: Yuanjy
 * @Date: 2020-03-09 20:41:15
 * @LastEditors: 任飞
 * @LastEditTime: 2020-07-02 09:51:23
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/menu'
import { filterAsyncRouter } from './store/modules/permission'
// import MockRouter from "@/utils/router-mock.js"

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login', '/wwxLogin', '/404', '/405', '/401', '/authPage', '/wwxThirdLogin']// no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      //debugger
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => { // 拉取user_info
          //debugger
          buildMenus().then(res => {
           // debugger
            const asyncRouter = filterAsyncRouter(res.data)
            asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
            store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
              debugger
              router.addRoutes(asyncRouter) // 动态添加可访问路由表
              next({ ...to, replace: true })// hack方法 确保addRoutes已完成
            })
          })
        }).catch((err) => {
          //debugger
          console.log(err)
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else {
        next()
      }
      // buildMenus().then(res => {
      //   const asyncRouter = filterAsyncRouter(res.data)
      //   console.log(asyncRouter)
      //   asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
      //   store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      //     router.addRoutes(asyncRouter) // 动态添加可访问路由表
      //     next({ ...to, replace: true })// hack方法 确保addRoutes已完成
      //   })
      // })
      // next()
    }
  } else {
    /* 登录的二维码页面 */
    if (to.path.search('/qrcode') !== -1) {
      next()
    } else if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
